package app

import "github.com/fuxiaohei/hxgo"

// App Controller struct
type Controller struct {
	hxgo.Controller
	Title string
	Data map[string]interface {}
	Nest  []string
}

// overwrite init func
// init this.Data map
func (this *Controller) Init() {
	this.Data = map[string]interface {}{}
	this.Nest = []string{}
}

// abort controller
// panic message and goto error handler in app.Handler
func (this *Controller) Abort(msg string) {
	panic(msg)
}

// return is ajax or not
func (this *Controller) IsAjax() bool {
	return this.R.IsAjax()
}

// return params are in this order
func (this *Controller) Param(p...string) bool {
	if len(p) < 1 {
		return true
	}
	// fix empty string case
	if len(this.R.Param) == 0 && len(p) == 1 && p[0] == "" {
		return true
	}
	// if order params are more than R.Param, comparing one by one is useless
	if len(this.R.Param) < len(p) {
		return false
	}
	// compare one by one
	for i, v := range p {
		if this.R.Param[i] != v {
			return false
		}
	}
	return true
}

// redirect to url
func (this *Controller) Redirect(url string) {
	this.Rs.Redirect(url)
}

// display template
// template data are this.Data map
// this.Title,this.R,this.Rs will be assigned to template data
// if render error, do this.Abort(errorMessage)
func (this *Controller) Display(tpl string) {
	this.Data["Title"] = this.Title
	this.Data["R"] = this.R
	this.Data["Rs"] = this.Rs
	var e error
	this.Rs.Content, e = View.Render(tpl, this.Data, this.Nest)
	if e != nil {
		this.Abort(e.Error())
	}
}

// json response
// this.Data will be encoded
// if json encoding error, do this.Abort(errorMessage)
func (this *Controller) Json() {
	e := this.Rs.Json(this.Data)
	if e != nil {
		this.Abort(e.Error())
	}
}

